﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SKIT.FlurlHttpClient.Wechat.TenpayV3;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Models;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Settings;

namespace AiQiuQuan.Sport.Core.WechatPayV3
{
    /// <summary>
    /// 微信支付平台证书自动刷新后台服务
    /// </summary>
    public class WechatPayV3CertificateRefreshBackgroundService : BackgroundService
    {
        private readonly ILogger<WechatPayV3CertificateRefreshBackgroundService> _logger;
        private readonly IOptions<WechatPayOption> _options;
        private readonly IWechatPayV3HttpClientFactory _wechatPayV3HttpClientFactory;

        public WechatPayV3CertificateRefreshBackgroundService(
            ILogger<WechatPayV3CertificateRefreshBackgroundService> logger,
            IOptions<WechatPayOption> options,
            IWechatPayV3HttpClientFactory wechatPayV3HttpClientFactory)
        {
            _logger = logger;
            _options = options;
            _wechatPayV3HttpClientFactory = wechatPayV3HttpClientFactory;
        }

        /// <summary>
        /// 执行
        /// </summary>
        protected async override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    var client = _wechatPayV3HttpClientFactory.Create(_options.Value.MchId);
                    var request = new QueryCertificatesRequest();
                    var response = await client.ExecuteQueryCertificatesAsync(request, cancellationToken: stoppingToken);
                    if (response.IsSuccessful())
                    {
                        // NOTICE:
                        //   如果启用了 `AutoDecryptResponseSensitiveProperty` 配置项，则无需再手动执行下面被注释的解密方法：
                        //   response = client.DecryptResponseSensitiveProperty(response);

                        response = client.DecryptResponseSensitiveProperty(response);
                        foreach (var certificateModel in response.CertificateList)
                        {
                            client.PlatformCertificateManager.AddEntry(new CertificateEntry(certificateModel));
                        }

                        _logger.LogInformation("刷新微信商户平台证书成功。");
                    }
                    else
                    {
                        _logger.LogWarning(
                            "刷新微信商户平台证书失败（状态码：{0}，错误代码：{1}，错误描述：{2}）。",
                            response.RawStatus, response.ErrorCode, response.ErrorMessage
                        );
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "刷新微信商户平台证书遇到异常。");
                }

                // 每隔 1 天轮询刷新,没有必要频繁刷新
                await Task.Delay(TimeSpan.FromDays(1));
            }
        }
    }
}
